import sys
import cv2
# from PyQt5.QtGui import *
# from PyQt5.QtWidgets import *
# from PyQt5.QtCore import *
import matplotlib.pyplot as plt
from PyQt5 import QtWidgets,QtCore,QtGui
from PyQt5.QtCore import Qt
from custom.stackedWidget import StackedWidget
from custom.treeView import FileSystemTreeView
from custom.listWidgets import FuncListWidget, UsedListWidget
from custom.graphicsView import GraphicsView
from pyqtconsole.console import PythonConsole
import qss_rc
import numpy as np

import pyqtgraph as pg
from pyqtgraph.Qt import QtGui
# from pyqtgraph import PlotWidget
# Interpret image data as row-major instead of col-major
def pgWidget():
    pg.setConfigOptions(imageAxisOrder='row-major')

    pg.mkQApp()
    win = pg.GraphicsLayoutWidget()
    win.setWindowTitle('pyqtgraph example: Image Analysis')

    # A plot area (ViewBox + axes) for displaying the image
    p1 = win.addPlot(title="")

    # Item for displaying image data
    img = pg.ImageItem()
    p1.addItem(img)

    # Custom ROI for selecting an image region
    roi = pg.ROI([-8, 14], [6, 5])
    roi.addScaleHandle([0.5, 1], [0.5, 0.5])
    roi.addScaleHandle([0, 0.5], [0.5, 0.5])
    p1.addItem(roi)
    roi.setZValue(10)  # make sure ROI is drawn above image

    # Isocurve drawing
    iso = pg.IsocurveItem(level=0.8, pen='g')
    iso.setParentItem(img)
    iso.setZValue(5)

    # Contrast/color control
    hist = pg.HistogramLUTItem()
    hist.setImageItem(img)
    win.addItem(hist)

    # Draggable line for setting isocurve level
    isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g')
    hist.vb.addItem(isoLine)
    hist.vb.setMouseEnabled(y=False) # makes user interaction a little easier
    isoLine.setValue(0.8)
    isoLine.setZValue(1000) # bring iso line above contrast controls

    # Another plot area for displaying ROI data
    win.nextRow()
    p2 = win.addPlot(colspan=2)
    p2.setMaximumHeight(250)
    # win.resize(800, 800)
    # win.show()


    # Generate image data
    data = np.random.normal(size=(200, 100))
    data[20:80, 20:80] += 2.
    data = pg.gaussianFilter(data, (3, 3))
    data += np.random.normal(size=(200, 100)) * 0.1
    img.setImage(data)
    hist.setLevels(data.min(), data.max())

    # build isocurves from smoothed data
    iso.setData(pg.gaussianFilter(data, (2, 2)))

    # set position and scale of image
    tr = QtGui.QTransform()
    img.setTransform(tr.scale(0.2, 0.2).translate(-50, 0))

    # zoom to fit imageo
    p1.autoRange()  


    # Callbacks for handling user interaction
    def updatePlot():
        # global img, roi, data, p2
        selected = roi.getArrayRegion(data, img)
        p2.plot(selected.mean(axis=0), clear=True)

    roi.sigRegionChanged.connect(updatePlot)
    updatePlot()

    def updateIsocurve():
        # global isoLine, iso
        iso.setLevel(isoLine.value())

    isoLine.sigDragged.connect(updateIsocurve)

    def imageHoverEvent(event):
        """Show the position, pixel, and value under the mouse cursor.
        """
        if event.isExit():
            p1.setTitle("")
            return
        pos = event.pos()
        i, j = pos.y(), pos.x()
        i = int(np.clip(i, 0, data.shape[0] - 1))
        j = int(np.clip(j, 0, data.shape[1] - 1))
        val = data[i, j]
        ppos = img.mapToParent(pos)
        x, y = ppos.x(), ppos.y()
        p1.setTitle("pos: (%0.1f, %0.1f)  pixel: (%d, %d)  value: %.3g" % (x, y, i, j, val))

    # Monkey-patch the image to use our custom hover function. 
    # This is generally discouraged (you should subclass ImageItem instead),
    # but it works for a very simple use like this. 
    img.hoverEvent = imageHoverEvent
    return win
class MyWin(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.tool_bar = self.addToolBar('工具栏')
        self.action_right_rotate = QtWidgets.QAction(QtGui.QIcon("icons/右旋转.png"), "向右旋转90", self)
        self.action_left_rotate = QtWidgets.QAction(QtGui.QIcon("icons/左旋转.png"), "向左旋转90°", self)
        self.action_histogram = QtWidgets.QAction(QtGui.QIcon("icons/直方图.png"), "直方图", self)
        self.action_right_rotate.triggered.connect(self.right_rotate)
        self.action_left_rotate.triggered.connect(self.left_rotate)
        self.action_histogram.triggered.connect(self.histogram)
        self.tool_bar.addActions((self.action_left_rotate, self.action_right_rotate, self.action_histogram))

        self.useListWidget = UsedListWidget(self)
        self.funcListWidget = FuncListWidget(self)
        self.stackedWidget = StackedWidget(self)
        self.fileSystemTreeView = FileSystemTreeView(self)
        self.graphicsView = GraphicsView(self)
        self.graphicsView.moved.connect(self.show_pos)
        self.dock_file = QtWidgets.QDockWidget(self)
        self.dock_file.setWidget(self.fileSystemTreeView)
        self.dock_file.setTitleBarWidget(QtWidgets.QLabel('目录'))
        self.dock_file.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)

        self.dock_func = QtWidgets.QDockWidget(self)
        self.dock_func.setWidget(self.funcListWidget)
        self.dock_func.setTitleBarWidget(QtWidgets.QLabel('图像操作'))
        self.dock_func.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)

        self.dock_used = QtWidgets.QDockWidget(self)
        self.dock_used.setWidget(self.useListWidget)
        self.dock_used.setTitleBarWidget(QtWidgets.QLabel('已选操作'))
        self.dock_used.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)
        self.dock_used.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)

        self.dock_attr = QtWidgets.QDockWidget(self)
        self.dock_attr.setWidget(self.stackedWidget)
        self.dock_attr.setTitleBarWidget(QtWidgets.QLabel('属性'))
        self.dock_attr.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)
        self.dock_attr.close()

        self.dock_pg = QtWidgets.QDockWidget(self)
        self.dock_pg.setWidget(pgWidget())
        self.dock_pg.setTitleBarWidget(QtWidgets.QLabel('属性'))
        self.dock_pg.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)

        self.dock_console = QtWidgets.QDockWidget(self)
        self.console=PythonConsole()
        self.console.push_local_ns('app', QtWidgets.qApp)
        self.console.push_local_ns('mainw', self)
        self.console.push_local_ns('cv2', cv2)
        self.dock_console.setWidget(self.console)
        # self.console.eval_in_thread()
        self.console.eval_queued()
        self.dock_console.setTitleBarWidget(QtWidgets.QLabel('console'))
        self.dock_console.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)

        self.setCentralWidget(self.graphicsView)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock_file)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock_pg)
        self.addDockWidget(Qt.TopDockWidgetArea, self.dock_func)
        self.addDockWidget(Qt.RightDockWidgetArea, self.dock_used)
        self.addDockWidget(Qt.RightDockWidgetArea, self.dock_attr)
        self.addDockWidget(Qt.BottomDockWidgetArea, self.dock_console)
        self.setWindowTitle('Opencv图像处理')
        self.setWindowIcon(QtGui.QIcon('icons/main.png'))

        self.statusbar = QtWidgets.QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)
        self.label=QtWidgets.QLabel(self)
        self.label.setText("hello")
        self.statusbar.addWidget(self.label)
        self.src_img = None
        self.cur_img = None
    def show_pos(self,x,y,val):
        # logging.info("show_pos",x,y)
        self.label.setText(str(x)+","+str(y)+":"+str(val))
    def update_image(self):
        if self.src_img is None:
            return
        img = self.process_image()
        self.cur_img = img
        self.graphicsView.update_image(img)

    def show_image(self,img):
        self.cur_img = img
        self.graphicsView.change_image(img)
    def show_cnt(self,i):
        app=QtWidgets.qApp
        if(i<len(app.cnts)):
            cnt=app.cnts[i]
            bbox = cv2.boundingRect(cnt)
            (x, y, w, h)=bbox
            img = cv2.rectangle(self.cur_img, (x, y), (x + w, y + h), (255, 0, 0), thickness=1)
            self.show_image(img)
    def change_image(self, img):
        self.src_img = img
        img = self.process_image()
        self.cur_img = img
        self.graphicsView.change_image(img)

    def process_image(self):
        # logging.debug("process_image ============")
        img = self.src_img.copy()
        for i in range(self.useListWidget.count()):
            img = self.useListWidget.item(i)(img)
        return img

    def right_rotate(self):
        self.graphicsView.rotate(90)

    def left_rotate(self):
        self.graphicsView.rotate(-90)

    def histogram(self):
        color = ('b', 'g', 'r')
        for i, col in enumerate(color):
            histr = cv2.calcHist([self.cur_img], [i], None, [256], [0, 256])
            histr = histr.flatten()
            plt.plot(range(256), histr, color=col)
            plt.xlim([0, 256])
        plt.show()

def qingyun_style(a):
    # f=open("qss/lightblue.css", "r") 
    f=open("qss/blacksoft.css", "r") 
    # f=open("qss/flatgray.css", "r") 
    _style = f.read()
    f.close()
    # logging.debug(_style)
    paletteColor=_style[20:20+7]
    # logging.debug(paletteColor)
    a.setPalette(QtGui.QPalette(QtGui.QColor(paletteColor)));
    a.setStyleSheet(_style);
def github_style(a):
    # with open("qss/ManjaroMix.qss", "r") as f:
    # with open("qss/Ubuntu.qss", "r") as f:
    # with open("qss/NeonButtons.qss", "r") as f:
    f=open("qss/MaterialDark.qss", "r")
    # with open("qss/AMOLED.qss", "r") as f:
    # with open("qss/ConsoleStyle.qss", "r") as f:
    # f=open("qss/MacOS.qss", "r")
    # f=open("qss/ElegantDark.qss", "r")
    a.setStyleSheet(f.read());
if __name__ == "__main__":
    from getpath import getpath
    import os
    import logging
    from logging.handlers import RotatingFileHandler
    from PyQt5 import QtWidgets
    handlers=[RotatingFileHandler(filename="cv.log", maxBytes=10*1024*1024,backupCount=3),# logging.FileHandler(initpath+'/myapp.log'),
            logging.StreamHandler(sys.stdout)
    ]
    # handlers=[logging.StreamHandler(sys.stdout)]
    logging.basicConfig(level=logging.DEBUG,
                        format = '%(asctime)s - %(name)s - %(levelname)s -%(funcName)s - %(message)s',
                        handlers=handlers)
    logging.info('begin')
    app = QtWidgets.QApplication(sys.argv)
    # f=open('./custom/styleSheet.qss', encoding='utf-8')
    # c=f.read()
    # f.close()
    # app.setStyleSheet(c)
    qingyun_style(app)
    window = MyWin()
    app.mainw=window
    window.show()
    sys.exit(app.exec())
